import { useState, useEffect } from "react"
import { useRequest } from "ahooks"

function useOnOk(asyncFun) {
  const { run } = useRequest(asyncFun, { manual: true, loadingDelay: 1000 })
  return {
    onOk: (fieldsValue) => run(fieldsValue)
  }
}
function useFormModal({ modal, service, defaultFormData, confirm, ...rest }) {
  const [visible, setVisible] = useState(false)
  const [formData, setFormData] = useState({})

  useEffect(() => {
    setFormData(defaultFormData || {})
  }, [defaultFormData])

  const { onCancel, ...restModalProps } = modal
  const { onOk } = useOnOk(service)
  const modalProps = {
    open: visible,
    maskClosable: false,
    onCancel() {
      setVisible(false)
      onCancel && onCancel()
    },
    destroyOnClose: true,
    ...restModalProps
  }

  return { modalProps, setVisible, formData, setFormData, confirm: confirm || onOk, ...rest }
}

export default useFormModal
